class http {
  constructor() {
    this.http = new XMLHttpRequest();
  }

  instance () {

  }

  post ({
    onProgress = e => { },
    url,
    params,
    headers,
    method = "POST"
  }) {
    return new Promise((resolve, reject) => {
      let formData = new FormData(); // XMLHttpRequest提交form表单数据，包括上传文件
      if ("[object FormData]" === Object.prototype.toString.call(params)) {
        formData = params;
      } else {
        for (const key in params) {
          formData.append(key, params[key]);
        }
      }

      for (const key of Object.keys(headers || {})) {
        this.http.setRequestHeader(key, headers[key]);
      }

      this.http.onprogress = onProgress;
      this.http.open(method, url);
      this.http.onreadystatechange = function () {
        if (this.readyState === 4) {
          if (this.status === 200) {
            const responseText = this.responseText;
            try {
              const response = 'string' === typeof responseText
                ? JSON.parse(responseText) : responseText;
              resolve(response, this)
            } catch (error) {
              resolve(responseText, this)
            }
          } else {
            const resJson = { code: this.status, response: this.response }
            reject(resJson, this)
          }
        }
      }

      this.http.send(formData);
    });
  }

}